﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using iWare.Wms.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 供应商首页服务
    /// </summary>
    [Route("api/HomePage")]
    [ApiDescriptionSettings("供应商模块", Name = "HomePage", Order = 100)]

    public class HomePageService : IDynamicApiController, ITransient
    {
        private readonly IRepository<PurchaseOrder, MasterDbContextLocator> _purchaseOrderRep; //采购订单仓储
        private readonly IRepository<GoodsDelivery, MasterDbContextLocator> _goodsDeliveryRep; //送货单仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="purchaseOrderRep"></param>
        /// <param name="goodsDeliveryRep"></param>
        public HomePageService(
            IRepository<PurchaseOrder, MasterDbContextLocator> purchaseOrderRep,
            IRepository<GoodsDelivery, MasterDbContextLocator> goodsDeliveryRep
            )
        {
            _purchaseOrderRep = purchaseOrderRep;
            _goodsDeliveryRep = goodsDeliveryRep;
        }
        #endregion

        /// <summary>
        /// 本月送货率
        /// </summary>
        /// <returns></returns>
        [HttpGet("MonthDeliveryTotal")]
        public async Task<List<DeliveryMonthOutput>> MonthDeliveryTotal()
        {
            var userId = CurrentUserInfo.UserId;

            var startTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd 00:00:00");
            var endTime = DateTime.Now.AddDays(-DateTime.Now.AddMonths(1).Day + 1)
                .AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59");

            //查询本月送货单详情
            var goodsDelivery = await _goodsDeliveryRep.DetachedEntities
                .Where(z => z.CreatedTime >= Convert.ToDateTime(startTime)
                 && z.CreatedTime <= Convert.ToDateTime(endTime))
                .Where(t => t.CreatedUserId == userId)
                .ToListAsync();


            var ListDeliveryMonth = new List<DeliveryMonthOutput>();

            var deliveryMonth = new DeliveryMonthOutput 
            { Name = "", Value = goodsDelivery.Where(z => z.Status == AuditStatusEnum.yuyuechenggong).Count()};
            ListDeliveryMonth.Add(deliveryMonth);

            return ListDeliveryMonth;
        }

        /// <summary>
        ///本周送货明细
        /// </summary>
        /// <returns></returns>
        [HttpGet("WeekdeliveryDetails")]
        public async Task<List<DeliveryWeekAndMonthOutput>> WeekdeliveryDetails()
        {
            var userId = CurrentUserInfo.UserId;

            //近七天
            int days = -7;

            //查询近一周的送货单详情
            var list = await _goodsDeliveryRep.DetachedEntities.
                Where(p => p.CreatedTime >= DateTime.Now.Date.AddDays(days)).ToListAsync();

            //给送货单详情输出参数赋值
            var deliveryWeekList = new List<DeliveryWeekAndMonthOutput>();
            for (int i = days; i <= 0; i++)
            {
                var starttime = DateTime.Now.Date.AddDays(i);
                var endtime = DateTime.Now.Date.AddDays(i + 1);
                var deliveryList = list.Where(p => p.CreatedTime >= starttime && p.CreatedTime <= endtime).ToList();
                var deliveryWeek = new DeliveryWeekAndMonthOutput()
                {
                    Quantity = deliveryList.Sum(t => t.DeliveryQuantityTotal),
                    dateStr = starttime.ToString("MM/dd")
                };
                deliveryWeekList.Add(deliveryWeek);
            }

            return deliveryWeekList;
        }

        /// <summary>
        /// 本年送货明细
        /// </summary>
        /// <returns></returns>
        [HttpGet("YearDeliveryDetails")]
        public async Task<DeliveryYearOutput> YearDeliveryDetails()
        {
            var quantitys = new List<decimal>();

            var userId = CurrentUserInfo.UserId;

            var startTime = DateTime.Now.AddDays(-DateTime.Now.DayOfYear + 1)
                .ToString("yyyy-MM-dd 00:00:00");
            var yearTime = DateTime.Now.AddYears(1);
            var endTime = DateTime.Now.AddDays(-yearTime.DayOfYear + 1)
                .AddYears(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59");

            var list = await _goodsDeliveryRep.DetachedEntities
                .Where(z => z.CreatedTime >= Convert.ToDateTime(startTime)
                 && z.CreatedTime <= Convert.ToDateTime(endTime))
                .Where(t => t.CreatedUserId == userId).ToListAsync();
            // 一月份
            var januaryQuantity = list.Where(z => z.CreatedTime?.Date.Month == 1)
                                            .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(januaryQuantity);
            // 二月份
            var februaryQuantity = list.Where(z => z.CreatedTime?.Date.Month == 2)
                                             .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(februaryQuantity);
            // 三月份
            var marchQuantity = list.Where(z => z.CreatedTime?.Date.Month == 3)
                                          .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(marchQuantity);
            // 四月份
            var aprilQuantity = list.Where(z => z.CreatedTime?.Date.Month == 4)
                                          .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(aprilQuantity);
            // 五月份
            var mayQuantity = list.Where(z => z.CreatedTime?.Date.Month == 5)
                                        .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(mayQuantity);
            // 六月份
            var juneQuantity = list.Where(z => z.CreatedTime?.Date.Month == 6)
                                         .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(juneQuantity);
            // 七月份
            var julyQuantity = list.Where(z => z.CreatedTime?.Date.Month == 7)
                                         .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(julyQuantity);
            // 八月份
            var augustQuantity = list.Where(z => z.CreatedTime?.Date.Month == 8)
                                           .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(augustQuantity);
            // 九月份
            var septemberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 9)
                                              .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(septemberQuantity);
            // 十月份
            var octoberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 10)
                                            .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(octoberQuantity);
            // 十一月份
            var novemberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 11)
                                             .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(novemberQuantity);
            // 十二月份
            var decemberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 12)
                                             .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(decemberQuantity);

            return new DeliveryYearOutput
            {
                Quantitys = quantitys
            };
        }

        /// <summary>
        /// 本月合格率总数（合格率=1-不合格率（不合格率＝不合格数量÷总数量×100%））
        /// </summary>
        /// <returns></returns>
        [HttpGet("MonthPassRateTotal")]
        public async Task<decimal> MonthPassRateTotal()
        {
            var userId = CurrentUserInfo.UserId;

            var startTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd 00:00:00");
            var endTime = DateTime.Now.AddDays(-DateTime.Now.AddMonths(1).Day + 1)
                .AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59");

            var goodsDeliveryList = await _goodsDeliveryRep.DetachedEntities
                .Where(t => t.CreatedTime > DateTime.Now.AddDays(-Convert.ToInt32(DateTime.Now.Date.Year)))
                .Where(t => t.CreatedUserId == userId).ToListAsync();
            // step2 根据采购单号去重
            var purchaseNoDistinct = goodsDeliveryList.Select(t => t.PurchaseNo)
                .Distinct().ToList();

            // step3 根据采购单号查询采购总数
            var purchaseOrderList = await _purchaseOrderRep
                .Where(z => purchaseNoDistinct.Contains(z.PurchaseNo)).ToListAsync();

            if (purchaseOrderList.Count > 0)
            {
                var quantityTotal = goodsDeliveryList
                    .Sum(t => t.DeliveryQuantityTotal) / purchaseOrderList
                    .Sum(t => t.PurchaseNumber) * 100;
                return Math.Round(quantityTotal, 2);
            }
            else
                return new decimal(0.00);
        }

        /// <summary>
        /// 本周合格率明细（合格率=1-不合格率（不合格率＝不合格数量÷总数量×100%））
        /// </summary>
        /// <returns></returns>
        [HttpGet("WeekPassRateDetails")]
        public async Task<List<DeliveryWeekAndMonthOutput>> WeekPassRateDetails()
        {
            var userId = CurrentUserInfo.UserId;

            //近七天
            int days = -7;

            //查询近一周的送货单详情
            var list = await _goodsDeliveryRep.DetachedEntities.
                Where(p => p.CreatedTime >= DateTime.Now.Date.AddDays(days)).ToListAsync();

            //给送货单详情输出参数赋值
            var deliveryWeekList = new List<DeliveryWeekAndMonthOutput>();
            for (int i = days; i <= 0; i++)
            {
                var starttime = DateTime.Now.Date.AddDays(i);
                var endtime = DateTime.Now.Date.AddDays(i + 1);
                var deliveryList = list.Where(p => p.CreatedTime >= starttime && p.CreatedTime <= endtime).ToList();
                var deliveryWeek = new DeliveryWeekAndMonthOutput()
                {
                    Quantity = deliveryList.Sum(t => t.DeliveryQuantityTotal),
                    dateStr = starttime.ToString("MM/dd")
                };
                deliveryWeekList.Add(deliveryWeek);
            }

            return deliveryWeekList;
        }

        /// <summary>
        /// 本年合格率明细（合格率=1-不合格率（不合格率＝不合格数量÷总数量×100%））
        /// </summary>
        /// <returns></returns>
        [HttpGet("YearPassRateDetails")]
        public async Task<DeliveryYearOutput> YearPassRateDetails()
        {
            var quantitys = new List<decimal>();

            var userId = CurrentUserInfo.UserId;

            var startTime = DateTime.Now.AddDays(-DateTime.Now.DayOfYear + 1)
                .ToString("yyyy-MM-dd 00:00:00");
            var yearTime = DateTime.Now.AddYears(1);
            var endTime = DateTime.Now.AddDays(-yearTime.DayOfYear + 1).AddYears(1)
                .AddDays(-1).ToString("yyyy-MM-dd 23:59:59");

            var list = await _goodsDeliveryRep.DetachedEntities
                .Where(t => t.CreatedTime > DateTime.Now.AddDays(-Convert.ToInt32(DateTime.Now.Date.Year)))
                .Where(t => t.CreatedUserId == userId).ToListAsync();
            // step2 根据采购单号去重
            var purchaseNoDistinct = list.Select(t => t.PurchaseNo).Distinct().ToList();

            // step3 根据采购单号查询采购总数
            var purchaseOrderList = await _purchaseOrderRep
                .Where(z => purchaseNoDistinct.Contains(z.PurchaseNo)).ToListAsync();

            // 一月份
            var januaryQuantity = list.Where(z => z.CreatedTime?.Date.Month == 1)
                                            .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(januaryQuantity);
            // 二月份
            var februaryQuantity = list.Where(z => z.CreatedTime?.Date.Month == 2)
                                             .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(februaryQuantity);
            // 三月份
            var marchQuantity = list.Where(z => z.CreatedTime?.Date.Month == 3)
                                          .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(marchQuantity);
            // 四月份
            var aprilQuantity = list.Where(z => z.CreatedTime?.Date.Month == 4)
                                          .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(aprilQuantity);
            // 五月份
            var mayQuantity = list.Where(z => z.CreatedTime?.Date.Month == 5)
                                        .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(mayQuantity);
            // 六月份
            var juneQuantity = list.Where(z => z.CreatedTime?.Date.Month == 6)
                                         .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(juneQuantity);
            // 七月份
            var julyQuantity = list.Where(z => z.CreatedTime?.Date.Month == 7)
                                         .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(julyQuantity);
            // 八月份
            var augustQuantity = list.Where(z => z.CreatedTime?.Date.Month == 8)
                                           .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(augustQuantity);
            // 九月份
            var septemberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 9)
                                              .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(septemberQuantity);
            // 十月份
            var octoberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 10)
                                            .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(octoberQuantity);
            // 十一月份
            var novemberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 11)
                                             .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(novemberQuantity);
            // 十二月份
            var decemberQuantity = list.Where(z => z.CreatedTime?.Date.Month == 12)
                                             .ToList().Sum(t => t.DeliveryQuantityTotal);
            quantitys.Add(decemberQuantity);

            return new DeliveryYearOutput
            {
                Quantitys = quantitys
            };
        }
    }
}
